package com.module.overview.ui.cardHistoryDetails.provider

import android.widget.TextView
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.data.bean.overView.HistoryDetailsModel
import com.common.base.app.extras.doOnUiThread
import com.common.base.utils.ViewUtils
import com.module.ble.repo.BodyTemperatureRepo
import com.module.ble.utils.AllCardTypeConfig
import com.module.overview.R

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/7/11
 *
 * 描述：体征-体温卡片
 *
 * 修订历史：完成度100%
 *
 */
class OvSignsTempCardProvider(time:Long,
    override val itemViewType: Int = AllCardTypeConfig.TYPE_CARD_SIGNS_TEMP,
    override val layoutId: Int = R.layout.overview_signs_temp_crad_provider
) : BaseItemProvider<HistoryDetailsModel>() {

    private var curTime = time

    private var tvTheDayAverage: TextView? = null
    private var tvRefTemp: TextView? = null
    private var tvTempDif: TextView? = null

    init {
    }

    override fun convert(helper: BaseViewHolder, item: HistoryDetailsModel) {
        getTheDayBodyTempData()
    }


    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {

        tvTheDayAverage = viewHolder.getView(R.id.tvTheDayAverage)
        tvRefTemp = viewHolder.getView(R.id.tvRefTemp)
        tvTempDif = viewHolder.getView(R.id.tvTempDif)

        super.onViewHolderCreated(viewHolder, viewType)
    }


    /**
     * 获取当天体温
     */
    private fun getTheDayBodyTempData(){
        if (curTime <=0) return

        get30DayBodyTempData(0)

        //睡眠体温
        BodyTemperatureRepo.instance.findAllByDay(curTime)?.let { listIt->

            if (listIt.isNullOrEmpty()) return

            val theDayAverage = if (listIt.isNotEmpty()) {//当日平均
                listIt.map { it.bodyTemperature }.average().toInt()
            } else {
                0f
            }
            get30DayBodyTempData(theDayAverage)

            doOnUiThread {
                tvTheDayAverage?.text = theDayAverage.toString()
            }

        }
    }


    /**
     * 获取30天体温
     */
    private fun get30DayBodyTempData(theDayAverage:Number){//取近7天(含今天)的所有数据算出基准和差值

        //睡眠体温
        BodyTemperatureRepo.instance.findLast7DaysFromTimestamp(curTime)?.let {listIt->
            if (listIt.isNullOrEmpty()) return

            val mDayAverage = if (listIt.isNotEmpty()) {//当日平均
                listIt.map { it.bodyTemperature }.average().toInt()
            } else {
                0f
            }

            doOnUiThread {
                tvRefTemp?.text = if (mDayAverage.toInt() <=0 ) { ViewUtils.getString(R.string.common_rail_unit) } else { mDayAverage.toInt().toString() }
                tvTempDif?.text = if ((theDayAverage.toFloat()- mDayAverage.toFloat()).toInt() <=0 ) { ViewUtils.getString(R.string.common_rail_unit) } else { (theDayAverage.toFloat()- mDayAverage.toFloat()).toString() }
            }

        }
    }
}